
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>

#define READ_END 0
#define WRITE_END 1
#define BUFFER_SIZE 50

/*
 * INFO
 *
 * The parent process will be the one that takes user input and
 * passes it to the child process through an ordinary pipe.
 *
 * The child process will read from that pipe and call my reverse()
 * function to switch all of the caps in the string. Then the child
 * will write back to the parent with a second pipe.
 *
 * The parent will read from that second pipe and display the results
 * of the child's work.
 */


/**
 * Reverse the capitals letters and lower case
 * letters in a char array.
 * @param string The char array to reverse. Should
 * be null terminated.
 */
void reverse(char string[]){

	int i = 0;
	while(string[i] != '\0'){
		if(string[i] >= 97 && string[i] <= 122){
			string[i] -= 32;
		}else if(string[i] >= 65 && string[i] <= 90){
			string[i] += 32;
		}
		i++;
	}

}

int pipes(int argc, char* argv[]){

	char write_str[BUFFER_SIZE];
	char read_str[BUFFER_SIZE];

	int parent_pipe[2];
	int child_pipe[2];



	if( pipe(parent_pipe) || pipe(child_pipe) ){
		printf("Error occurred during read, exiting\n");
		exit(1);
	}


	pid_t pid;
	pid = fork();

	if(!pid){ /* child */

		/* close the pipe ends that we don't need */
		close(parent_pipe[WRITE_END]);
		close(child_pipe[READ_END]);

		if(read(parent_pipe[READ_END], read_str, BUFFER_SIZE) < 0){
			printf("Error occurred during read, exiting\n");
			exit(1);
		}

		reverse(read_str); // function for reversing the caps of a string

		if(write(child_pipe[WRITE_END], read_str, (strlen(read_str)+1)) < 0){
			printf("Error occurred during write, exiting\n");
			exit(1);
		}

	}else{ /* parent */

		printf("Enter a string to reverse its caps: ");

		if(!fgets(write_str,BUFFER_SIZE,stdin)){
			printf("could not read from stdin, or no characters were found. Exiting\n");
			exit(1);
		}

		/* close the pipe ends that we don't need */
		close(parent_pipe[READ_END]);
		close(child_pipe[WRITE_END]);

		if(write(parent_pipe[WRITE_END], write_str, (strlen(write_str)+1)) < 0){
			printf("Error occurred during write, exiting\n");
			exit(1);
		}

		char reversed_str[BUFFER_SIZE];

		if(read(child_pipe[READ_END], reversed_str, BUFFER_SIZE) < 0){
			printf("Error occurred during read, exiting\n");
			exit(1);
		}

		printf("Reversed String: %s", reversed_str);
	}


	return 0;
}
